package com.itheima.stock.common.strategy;

import com.google.common.collect.Range;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingValue;
import org.joda.time.DateTime;

import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.stream.Collectors;

public class StockRtInfoTableRangeHandler implements RangeShardingAlgorithm<Date> {
    @Override
    public Collection<String> doSharding(Collection<String> availableTargetNames, RangeShardingValue<Date> shardingValue) {
        Range<Date> valueRange = shardingValue.getValueRange();
        Collection<String> filters=new HashSet<>();
        if (valueRange.hasLowerBound()) {
            Date startTime = valueRange.lowerEndpoint();
            String startStr = new DateTime(startTime).toString("yyyyMM");
            //过滤获取大于指定日期的值
            availableTargetNames = availableTargetNames.stream().filter(tbName -> {
                String numStr = tbName.substring(tbName.lastIndexOf("_") + 1);
                return Integer.valueOf(numStr) >= Integer.valueOf(startStr);
            }).collect(Collectors.toList());
        }
        if (valueRange.hasUpperBound()) {
            Date endTime = valueRange.upperEndpoint();
            String endStr = new DateTime(endTime).toString("yyyyMM");
            //过滤获取大于指定日期的值
            availableTargetNames = availableTargetNames.stream().filter(tbName -> {
                String numStr = tbName.substring(tbName.lastIndexOf("_") + 1);
                return Integer.valueOf(numStr) <= Integer.valueOf(endStr);
            }).collect(Collectors.toList());
        }
        return availableTargetNames;
    }
}